package com.hnqcgczy.controller;

import com.hnqcgczy.service.IUserService;
import com.hnqcgczy.service.impl.UserServiceImpl;
import com.hnqcgczy.utils.MD5Encryptor;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和相应的编码格式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //接收用户名  密码
        String tuId=req.getParameter("tuId");
        String password=req.getParameter("password");
        String userCaptcha=req.getParameter("userCaptcha");
        int captcha= (Integer)req.getSession().getAttribute("captcha");
        if(captcha!=Integer.parseInt(userCaptcha)){
            System.out.println("验证码错误");
            req.getSession().setAttribute("errCapt","验证码错误");
            resp.sendRedirect("/login.jsp");
        }else {
            req.getSession().setAttribute("errCapt","");
            //获取服务层对象
            IUserService uss = new UserServiceImpl();
            //返回登陆结果
            boolean flag = false;
            try {
                String md5pass = MD5Encryptor.encrypt(password);
                flag = uss.login(tuId, md5pass);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            //如果登陆成功，将用户名存储于session
            HttpSession session = req.getSession();
            if (flag) {
                session.setAttribute("tuId", tuId);
                // req.getRequestDispatcher("index.jsp").forward(req,resp);
                resp.sendRedirect("/home");
            } else {
                // req.getRequestDispatcher("login.jsp").forward(req,resp);
                req.getSession().setAttribute("errCapt","账号或密码错误");
                resp.sendRedirect("/login.jsp");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);
    }
}
